package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

//令牌校验过滤器
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;


        //1.获取请求url
        String uri = request.getRequestURI();   // /employee/login
//        String url = request.getRequestURL().toString(); // http://localhost:8080/employee/login

        //2.判断请求url中是否包含login，如果包含，证明是登陆操作，放行
        if(uri.contains("login")){
            log.info("登录请求，直接放行");
            chain.doFilter(request,response);
            return;
        }

        //3.获取请求头中的令牌(token)
        String token = request.getHeader("token");

        //4.判断令牌是否存在，如果不存在，返回错误结果（未登录）
//        if(!StringUtils.hasLength(jwt)){
//            log.info("获取到jwt令牌为空，返回错误结果");
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            return;
//        }

        if(token == null || token.isEmpty()){
            log.info("token为空，响应状态码401");
            response.setStatus(401);
            return;
        }

        //5.解析token，如果解析失败，返回错误结果（未登录）
//        try {
//            JwtUtils.parseJWT(token);
//        } catch (Exception e) {
//            log.info("解析令牌失败，返回错误结果");
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            return;
//        }

        try{
            Claims claims = JwtUtils.parseJWT(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("token解析成功，放行");
        }catch (Exception e){
            log.info("token解析失败，响应401状态码");
            response.setStatus(401);
            return;
        }

        //6.放行
        log.info("令牌合法，放行");
        chain.doFilter(request,response);


        //7.清空当前线程绑定的id
        CurrentHolder.remove();
    }
}
